package com.runen.infinitemovement.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.ColumnDetailsActivity;
import com.runen.infinitemovement.activity.SecondReplyCommentActivity;
import com.runen.infinitemovement.adapter.ContentsAdapter;
import com.runen.infinitemovement.model.api.ActivityAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.CommentDetailListBean;
import com.runen.infinitemovement.model.entity.MyLongMarchCommentEntity;
import com.runen.infinitemovement.model.entity.ReplyCommentListBean;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.widget.CustomLoadMoreView;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ContentsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rv_content)
    RecyclerView rvContent;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.edt_input_message)
    EditText edtInputMessage;
    @BindView(R.id.rl_bottom)
    LinearLayout rlBottom;
    private View view;
    private ContentsAdapter contentsAdapter;
    private String userId;
    private CommentDetailListBean commentDetailListBean;
    private ReplyCommentListBean replyCommentListBean;
    private String topItemCommentId;

    public static Fragment newInstance(String userId) {
        Fragment fragment = new ContentsFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userId", userId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_contents, container, false);
            ButterKnife.bind(this, view);
            userId = getArguments().getString("userId");
            initView();
            initData();
        }

        return view;
    }

    private void initView() {
        srl.setOnRefreshListener(this);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvContent.setLayoutManager(layoutManager);
        contentsAdapter = new ContentsAdapter(getActivity());
        contentsAdapter.getLoadMoreModule().setLoadMoreView(new CustomLoadMoreView());
        rvContent.setAdapter(contentsAdapter);


        contentsAdapter.setOnItemCommentClick(new ContentsAdapter.OnItemCommentClick() {
            @Override
            public void onItemPraise(CommentDetailListBean item) {

            }

            @Override
            public void onItemCommentReply(CommentDetailListBean item, String topCommentId) {
                //评论回复
                commentDetailListBean = item;
                topItemCommentId = topCommentId;
                edtInputMessage.setHint("回复" + item.nickname + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemSecondReply(ReplyCommentListBean item, String topCommentId) {
                replyCommentListBean = item;
                topItemCommentId = topCommentId;
                edtInputMessage.setHint("回复" + item.reviewerName + "：");
                CommonUtil.showKeyboard(edtInputMessage);
            }

            @Override
            public void onItemMore(CommentDetailListBean item, String topCommentId) {
                Intent intent = new Intent(getActivity(), SecondReplyCommentActivity.class);
                intent.putExtra("commentId", item.commentId);
                intent.putExtra("targetId", userId);
                startActivity(intent);
            }
        });

        edtInputMessage.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND) {//修改回车键功能
                    //代码
                    String edtString = v.getText().toString().trim();
                    if (TextUtils.isEmpty(edtString)) {
                        ToastUtils.showShort("请输入评论信息！！！");
                    } else {
                        onComment(edtString, commentDetailListBean, replyCommentListBean);
                    }
                }
                return false;
            }
        });
        iniLoadMore();
    }

    private void iniLoadMore() {
        contentsAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreRequested();
            }
        });
        contentsAdapter.getLoadMoreModule().setAutoLoadMore(true);
        contentsAdapter.getLoadMoreModule().setEnableLoadMoreIfNotFullPage(false);
    }


    /**
     * 对文章的评论
     *
     * @param edtString
     */
    private void onComment(String edtString, final CommentDetailListBean commentDetailList, final ReplyCommentListBean replyCommentList) {
        JSONObject object = new JSONObject();
        try {
            object.put("commentType", "2");
            object.put("content", edtString);
            object.put("targetId", UserAPI.getUserId());
            object.put("replyUserId", userId);
            if (null != commentDetailList) {
                object.put("replyId", commentDetailList.commentId);
                object.put("replyUserId", commentDetailList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            } else if (null != replyCommentList) {
                object.put("replyArticleCommentsId", replyCommentList.commentId);
                object.put("replyUserId", replyCommentList.reviewerId);
                object.put("topCommentId", topItemCommentId);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new ActivityAPI().onDynamicComment(object.toString(), new BaseResultCallback<BaseResponseEntity<?>>() {
            @Override
            public void onResponse(BaseResponseEntity<?> response) {

            }

            @Override
            public void onComplete() {
                super.onComplete();
                CommonUtil.hideKeyboard(getActivity());
                edtInputMessage.setText("");
                edtInputMessage.setHint("说点什么...");
                commentDetailListBean = null;
                replyCommentListBean = null;
                onRefresh();
            }
        });
    }


    private boolean isComment;

    @OnClick(R.id.ll_content)
    public void onViewClicked() {
        isComment = !isComment;
        if (isComment) {
            rlBottom.setVisibility(View.VISIBLE);
        } else {
            rlBottom.setVisibility(View.GONE);
        }
    }

    @Override
    public void onRefresh() {
        page = 2;
        initData();
    }

    private int page = 2;

    private void initData() {
        srl.setRefreshing(true);
        String string = "?commentType=2&limit=20&page=1";
        new ActivityAPI().getMyLongMarchComment(string, new BaseResultCallback<MyLongMarchCommentEntity>() {
            @Override
            public void onResponse(MyLongMarchCommentEntity response) {
                srl.setRefreshing(false);
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        contentsAdapter.setNewData(response.data);
                        if (contentsAdapter.getData().size() >= response.count) {
                            contentsAdapter.getLoadMoreModule().loadMoreEnd(true);
                            contentsAdapter.getLoadMoreModule().setEnableLoadMore(false);
                        }
                    }
                }
            }
        });
    }

    private void loadMoreRequested() {
        String string = "?commentType=2&limit=20&page=%s";
        new ActivityAPI().getMyLongMarchComment(String.format(string, page), new BaseResultCallback<MyLongMarchCommentEntity>() {
            @Override
            public void onResponse(MyLongMarchCommentEntity response) {
                if (response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        contentsAdapter.addData(response.data);
                        if (contentsAdapter.getData().size() >= response.count) {
                            contentsAdapter.getLoadMoreModule().loadMoreEnd(true);
                            contentsAdapter.getLoadMoreModule().setEnableLoadMore(false);
                        } else {
                            page++;
                            contentsAdapter.getLoadMoreModule().loadMoreComplete();
                            contentsAdapter.getLoadMoreModule().setEnableLoadMore(true);
                        }
                    }
                }
            }
        });
    }
}
